package xyz.jason.mybatisgenerator.util;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ProjectName: mybatis-generator
 * @Package: xyz.jason.mybatisgenerator.util
 * @ClassName: FileUtils
 * @Author: Jason · L
 * @Description: file工具类
 * @Date: 2021/4/7 10:39
 * @Version: 1.0
 */
@Slf4j
public class FileUtils {

    private FileUtils(){};


    //创建目录
    public static void fileMkDirs(String path){
        try {
            Files.createDirectories(Paths.get(path));
        } catch (IOException e) {
            log.error("创建目录异常",e);
        }
    }

    //删除目录
    public static void deleteMkDirs(String path){
        File file = new File(path);
        File[] files = file.listFiles();
        assert files != null;
        for (File f : files){
            if(f.isDirectory())
                deleteMkDirs(f.getPath());
            f.delete();
        }
    }

    //压缩文件
    @SneakyThrows
    public static String doZip(String zipPath,String directory){
        String fileName = System.currentTimeMillis()+".zip";
        try (ZipOutputStream stream = new ZipOutputStream(new FileOutputStream(zipPath + fileName))) {
            zip(stream,new File(directory));
        }
        return fileName;
    }



    //添加压缩文件
    private static void zip(ZipOutputStream stream,File file) {
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for (File f : files){
                if(!f.isDirectory()){
                    zipWrite(stream,f);
                }else{
                    zip(stream,f);
                }
            }
        }else{
            zipWrite(stream,file);
        }

    }


    //压缩写入
    @SneakyThrows
    private static void zipWrite(ZipOutputStream stream, File file){
        try (FileInputStream in = new FileInputStream(file)){
            stream.putNextEntry(new ZipEntry(file.getName()));
            int len ;
            byte [] bytes = new byte[1024];
            while ((len=in.read(bytes))!=-1)
                stream.write(bytes,0,len);
            stream.closeEntry();
        }
    }
}
